using System;
using System.Web.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using System.Web.Profile;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.WebControls;
using IWCommunity.Common;

namespace IWCommunity.UserRoleManagement
{
    /// <summary>
    /// Code behind for UserEdit.aspx
    /// </summary>
    public class UserEdit : LayoutsPageBase
    {
        protected InputFormSection GroupSection;
        protected InputFormSection RolesSection;
        protected InputFormCheckBoxList groupList;
        protected InputFormCheckBoxList rolesList;
        protected InputFormCheckBox isActive;
        protected InputFormTextBox txtEmail;
        protected InputFormTextBox txtPassword;
        protected InputFormTextBox txtFullName;
        protected InputFormTextBox txtUsername;
        protected Label lblMessage;

        private bool _showRoles;

        protected override bool RequireSiteAdministrator
        {
            get { return true; }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.CheckRights();
   
            // init
            _showRoles = true; //(this.Web.Features[new Guid("F3808A5F-354C-4216-BF9E-DCFA8C44F0FC")] != null);
            SPIisSettings settings = Utilities.GetFBAIisSettings(this.Site);

            // get user info
            string userName = this.Request.QueryString["USERNAME"];
            SPUser spuser = null;
            //spuser = this.Web.AllUsers[settings.MembershipProvider + ":" + userName];
            MembershipUser user = Membership.GetUser(userName);

            if (user != null)
            {
                if (!Page.IsPostBack)
                {
                    // load user props
                    txtEmail.Text = user.Email; //spUser.Email;
                    //txtFullName.Text = spuser.Name;
                    txtUsername.Text = user.UserName;
                    isActive.Checked = user.IsApproved;


                    //update user profile
                    ProfileBase userProfile = DefaultProfile.Create(user.UserName);
                    string fName = userProfile.GetPropertyValue("FirstName").ToString(); 
                    string lName = userProfile.GetPropertyValue("LastName").ToString(); //, lastName);
                    txtFullName.Text = fName + " " + lName;
                    
                    // if roles activated display roles
                    if (_showRoles)
                    {
                        RolesSection.Visible = true;
                        GroupSection.Visible = false;

                        try
                        {
                            // load roles
                            string[] roles = Roles.GetAllRoles();
                            rolesList.DataSource = roles;
                            rolesList.DataBind();

                            // select roles associated with the user
                            for (int i = 0; i < roles.Length; i++)
                            {
                                rolesList.Items.FindByText(roles[i].ToString()).Selected = Roles.IsUserInRole(user.UserName, roles[i].ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(ex, true);
                        }
                    }
                    // otherwise display groups
                    //else
                    //{
                    //    GroupSection.Visible = true;
                    //    RolesSection.Visible = false;

                    //    try
                    //    {
                    //        // load groups
                    //        groupList.DataSource = this.Web.Groups;
                    //        groupList.DataBind();

                    //        // select groups associated with the user
                    //        if (spuser != null)
                    //        {
                    //            foreach (SPGroup group in spuser.Groups)
                    //            {
                    //                groupList.Items.FindByText(group.Name).Selected = true;
                    //            }
                    //        }
                       
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Logger.LogError(ex, true);
                    //    }
                    //}
                }
            }
            else
            {
                SPUtility.TransferToErrorPage("User Not Found");
            }
        }

        protected void OnSubmit(object sender, EventArgs e)
        {
            // get user info
            SPIisSettings settings = Utilities.GetFBAIisSettings(this.Site);
            string userName = this.Request.QueryString["USERNAME"];
            //SPUser spuser = this.Web.AllUsers[settings.MembershipProvider + ":" + userName];
            MembershipUser user = Membership.GetUser(userName);
            
            // check user exists
            if (user != null)
            {
                try
                {
                    // update membership provider info
                    user.Email = txtEmail.Text;
                    user.IsApproved = isActive.Checked;
                    Membership.UpdateUser(user);

                    user.Email = txtEmail.Text;
                    Membership.UpdateUser(user);

                    ProfileBase userProfile = DefaultProfile.Create(user.UserName);
                    string[] name = txtFullName.Text.Split(" ".ToCharArray());
                    if (name.Length > 0)
                    {
                        userProfile.SetPropertyValue("FirstName",name[0]);
                        userProfile.SetPropertyValue("LastName",name[1]);
                    }
                    else
                        userProfile.SetPropertyValue("FirstName", txtFullName.Text);

                    userProfile.Save();
                    
                    
                    

                    // update sharepoint user info
                    //spuser.Email = txtEmail.Text;
                    //spuser.Name = txtFullName.Text;
                    //spuser.Update();
               
                    // if roles enabled add/remove user to selected role(s)
                    if (_showRoles)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                if (!Roles.IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                    Roles.AddUserToRole(user.UserName, rolesList.Items[i].Value);
                            }
                            else
                            {
                                if (Roles.IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                    Roles.RemoveUserFromRole(user.UserName, rolesList.Items[i].Value);
                            }
                        }
                    }
                    // or add/remove user to selected group(s)
                    //else
                    //{
                    //    for (int i = 0; i < groupList.Items.Count; i++)
                    //    {
                    //        string groupName = groupList.Items[i].Value;
                            
                    //        // determine whether user is in group
                    //        bool userInGroup = false;
                    //        foreach (SPGroup group in spuser.Groups)
                    //        {
                    //            if (group.Name == groupName)
                    //            {
                    //                userInGroup = true;
                    //                break;
                    //            }
                    //        }

                    //        // if selected add user to group
                    //        if (groupList.Items[i].Selected)
                    //        {
                    //            // only add if not already in group
                    //            if (!userInGroup)
                    //                this.Web.Groups[groupName].AddUser(spuser);
                    //        }
                    //        // else remove user from group
                    //        else
                    //        {
                    //            // only attempt remove if actually in the group
                    //            if (userInGroup)
                    //                this.Web.Groups[groupName].RemoveUser(spuser);
                    //        }
                    //    }
                    //}
                    Response.Redirect("UsersDisp.aspx");
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, true);
                }
            }
            else
            {
                SPUtility.TransferToErrorPage("User Not Found");
            }
        }
    }
}
